package com.selen.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.selen.result.Result;
import com.selen.result.ResultCode;
import com.selen.utils.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Selen
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        response.setContentType("application/json;charset=utf-8");

        // 若目标方法不是Controller方法，则直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 若请求头中不存在Token令牌，则返回失效提示
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            response.getWriter().print(JSONUtil.toJsonStr(new Result<>(ResultCode.TOKEN_FAILED))
            );
            return false;
        }

        // 解析Token令牌
        Map<String, Object> verifyResult = JWTUtil.verify(token);

        // 获取Token令牌的过期标记: true表示即将要过期
        boolean expiringSoon = (boolean) verifyResult.get("expiringSoon");

        // 若Token令牌即将过期，则返回过期提示以及一个新的Token令牌
        if (expiringSoon) {
            String newToken = (String) verifyResult.get("newToken");
            response.getWriter().print(
                    JSONUtil.toJsonStr(new Result<>(ResultCode.TOKEN_EXPIRING_SOON, newToken))
            );
            return false;
        }

        return true;
    }
}
